06. Adding Markers
L4 A05 Adding Markers
Reference Documentation
By default, the onMapReady() callback includes code that places a marker in Sydney, Australia, where Google Maps was created. The default callback also animates the map to pan to Sydney. In this step, you make the map’s camera move to your home, zoom to a level you specify and place a marker there.
- In the
onMapReady()method, remove the code that places the marker in Sydney and moves the camera. This is what your method should look like now.
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
}
- Find the latitude and longitude of your home by following these instructions.
- Create a value for the latitude and a value for the longitude and input their float values.
val latitude = 37.422160
val longitude = -122.084270
- Create a new
LatLngobject calledhome. In theLatLngobject, use the values you just created.
val homeLatLng = LatLng(latitude, longitude)
- Move the camera to home by calling the
moveCamera()function on theGoogleMapobject and pass in aCameraUpdateobject usingCameraUpdateFactory.newLatLngZoom(). Create a val for how zoomed in you want to be on the map.
The zoom level controls how zoomed in you are on the map. The following list gives you an idea of what level of detail each level of zoom shows:
- 1: World
- 5: Landmass/continent
- 10: City
- 15: Streets
- 20: Buildings
Pass in the home object and a float for how zoomed in you want it to be.
val zoomLevel = 15f
map.moveCamera(CameraUpdateFactory.newLatLngZoom(homeLatLng, zoomLevel))
- Add a marker to the map at your home.
map.addMarker(MarkerOptions().position(homeLatLng))
The method should look like this.
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
//These coordinates represent the latitude and longitude of the Googleplex.
val latitude = 37.422160
val longitude = -122.084270
val zoomLevel = 15f
val homeLatLng = LatLng(latitude, longitude)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(homeLatLng, zoomLevel))
map.addMarker(MarkerOptions().position(homeLatLng))
}
- Run the app. The map should pan to your home, zoom into the desired level and place a marker on your home.